package utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Scanner;

public class DateConverter {

	static Scanner scanner;
	static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd H:m");

	static public Date stringToDate(String time) throws ParseException {
		return dateFormat.parse(time);
	}

	static public String dateToString(Date date) {
		return dateFormat.format(date);
	}

	/**
	 * Checks that date is not like 9999/99/99 99:99
	 * 
	 * @return
	 */
	static public boolean validateDateFormat(String date) {
		if (!date.matches("[0-9]{4}/[0-9]{2}/[0-9]{2}\\s[0-9]{2}:[0-9]{2}")) {
			return false;
		}
		scanner = new Scanner(date);
		scanner.useDelimiter("/|\\s|:");
		int year = Integer.parseInt(scanner.next());
		int month = Integer.parseInt(scanner.next());
		int day = Integer.parseInt(scanner.next());
		int hour = Integer.parseInt(scanner.next());
		int minute = Integer.parseInt(scanner.next());
		if (year > 3000 || month > 12 || month == 0
				|| day > daysInMonth(month, year) || day == 0 || hour > 23
				|| minute > 60) {
			return false;
		}
		return true;
	}

	static private int daysInMonth(int monthNumber, int yearNumber) {
		GregorianCalendar cal = new GregorianCalendar(yearNumber, monthNumber-1, 1);
		return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
	}

}
